from MediaInfoDLL import * 
from PyFlac.Carbon import CarbonUtils
from PyFlac.Carbon import CarbonJob
from PyFlac.Carbon import CarbonSocketLayer
from PyFlac.Ardome import ArdXML
from PyFlac import TimeCode
import sys
import shutil

SMB_PATH_IN   = '\\\\10.221.173.151\\uti\\43\\'
#SMB_PATH_OUT  = '\\\\10.221.173.151\\uti\\out'
SMB_PATH_OUT  = '\\\\10.221.173.223\\To_Atlanta_Enconpass'
GUID_43       = '{F6F7C875-85D9-4CFC-B991-D67BE44A08FD}'
GUID_169      = '{5F3972E5-BFA3-49AD-8A5C-BF3FE8C98746}'	
XML	      = './PG-67281-2-ACTITUDFEMENINAYR22011-AFII07-EPISODIO7-JDJG.mxf.xml'
MXF	      = 'PG-67281-2-ACTITUDFEMENINAYR22011-AFII07-EPISODIO7-JDJG.mxf'
MEDIA_PATH    = '/data/Uti/43/'


def msToFrames(ms):
        f = 1000.0 / 29.97
        return int(round( ms / f ))




def CutSegment (mxf, start_tc_frames, tc_in, tc_out, basename, carbon_host, carbon_guid, src_path, dst_path):

	tcin  = TimeCode.TimeCode(tc_in)
	tcout = TimeCode.TimeCode(tc_out)

	framesin  = tcin.GetFramesFromZero() - start_tc_frames
        framesout = tcout.GetFramesFromZero() - start_tc_frames 

	cut_info = { 'in' : str(CarbonUtils.FramesToCarbonFramesUnit(framesin)), 'out': str(CarbonUtils.FramesToCarbonFramesUnit(framesout)) }
	
	carbon = CarbonSocketLayer.CarbonSocketLayer(carbon_host)

	jobXml = CarbonUtils.CreateCarbonXMLJob(src_path, mxf, [cut_info], [{'d_guid': carbon_guid, 'd_basename': basename, 'd_path': dst_path, 'd_start_tc': tc_in}])

	return CarbonJob.CarbonJob(carbon, jobXml)


def CutMediaSegments(mxf, Segments, carbon_host, carbon_guid, src_path, dst_path):
	
	if os.path.isfile(MEDIA_PATH+mxf):
		MI = MediaInfo()
		MI.Open(MEDIA_PATH+mxf)
		delay = MI.Get(Stream.Video, 0, u"Delay")
		MI.Close()
		
		# delay are in ms, needs convert to frames 
			
		frames =  msToFrames(int(delay))	
		for s in Segments:
			job = CutSegment(mxf, frames, s.SOM, s.EOM, "UTI" + s.seg_automation_id, carbon_host, carbon_guid, src_path, dst_path)
			job.Start()

list = os.listdir(MEDIA_PATH)
for i in list: 

	if not i.endswith(".xml"):
		continue	

	os.system("ascii " + MEDIA_PATH+i + " /tmp/"+i)
	

	
	xml = ArdXML.ArdXML("/tmp/"+i)

	shutil.move("/tmp/"+i, MEDIA_PATH+"proc/"+i)


	(mxf,e, x) = i.split(".")

	mxf = mxf + ".mxf"

	print "BASE: " + MEDIA_PATH+mxf
	os.remove(MEDIA_PATH+i)

	for s in xml.Metadata.segments:
		print s.SOM + '-' + s.EOM


	CutMediaSegments(mxf, xml.Metadata.segments, '10.221.173.31', GUID_43, SMB_PATH_IN, SMB_PATH_OUT)
